from lxml import etree
from framework.common import util
from framework.core.crawler_result import Result
from framework.core.crawler_task import Task


class QaParser(object):
    @staticmethod
    def parse(response, current_task):
        parent_result = current_task.parent_result
        content = response.content
        tree = etree.HTML(content)
        qa_list = list()

        div_qa_list = tree.xpath("//div[@class='a-section askTeaserQuestions']/div[@class='a-fixed-left-grid a-spacing-base']")
        for div_qa in div_qa_list:
            qa_dict = dict()
            question = div_qa.xpath("descendant::*/div[@class='a-fixed-left-grid-col a-col-right']/a/span/text()")
            qa_dict["question"] = util.fstring(question)

            answer = div_qa.xpath("descendant::*/div[@class='a-fixed-left-grid-col a-col-right']/span/text()")
            qa_dict["answer"] = util.fstring(answer)

            answer_author = div_qa.xpath("descendant::*/span[@class='a-profile-name']/text()")
            qa_dict["answer_author"] = util.fstring(answer_author)

            has_seller_flag = div_qa.xpath("descendant::*/div[@class='a-section a-spacing-none a-spacing-top-micro']/a/text()")
            qa_dict["has_seller_flag"] = len(has_seller_flag) > 0

            answer_date = div_qa.xpath("descendant::*/span[@class='a-color-tertiary aok-align-center']/text()")
            qa_dict["answer_date"] = util.fstring(answer_date)

            votes = div_qa.xpath("descendant::*/ul[@class='vote voteAjax']/li[boolean(@data-count)]/@data-count")
            qa_dict["votes"] = util.fstring(votes)

            other_answers_count = div_qa.xpath("descendant::*/div[@class='a-section a-spacing-none a-spacing-top-mini']/a/span/text()")
            qa_dict["other_answers_count"] = util.fstring(other_answers_count)

            other_answers_url = div_qa.xpath("descendant::*/div[@class='a-section a-spacing-none a-spacing-top-mini']/a/@href")
            qa_dict["other_answers_url"] = util.fstring(other_answers_url)

            qa_list.append(qa_dict)

        next_page_url = tree.xpath("//ul[@class='a-pagination']/li[@class='a-last']/a/@href")
        next_page_url = util.fstring(next_page_url)
        next_page_number = int(next_page_url.split("/")[-2])
        new_task_list = None
        if next_page_number <= 10:  # JimmyMo: grab max 10 pages of review
            new_task_list = Task.create_tasks("https://www.amazon.com" + util.fstring(next_page_url), parser=current_task.parser,
                                              parent_result=None,
                                              metadata=current_task.copy_metadata())

        review_result = Result.from_task(task=current_task, reviews=qa_list)
        return review_result, new_task_list


if __name__ == "__main__":
    import json
    from framework.mock import MockResponse, MockTask
    parser = QaParser()
    sampler_local_html = "./samples/qa_B01N1Z2HUS.html"
    response = MockResponse(sampler_local_html)
    parser.parse(response, MockTask(None))